package com.ja.openchat.ui.contact;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;

import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityContactChatSettingsBinding;
import com.ja.openchat.ui.chat.ForwardActivity;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.chat.SettingBackgroudActivity;
import com.ja.openchat.viewmodels.ContactChatSettingViewModel;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageContent;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.user.MobileContactInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import butterknife.OnClick;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class ContactChatSettingsActivity extends BaseActivity<ActivityContactChatSettingsBinding, ContactChatSettingViewModel> {

    public ChatInfo chatInfo;
    private UserFullInfo userFullInfo;

    public static void start(Activity activity, ChatInfo chat) {
        UserInfo userInfo = null;
        if (chat != null) {
            userInfo = TelegramManager.getTelegramManager().getTgData().contactInfo(chat.id);
            if(userInfo==null){
                userInfo = UserInfo.getUserInfo(chat.userId());
            }
            if(userInfo!=null){
                ContactDetailSingleActivity.start(activity,userInfo,chat.id,false);
            }else{
                ContactDetailSingleActivity.start(activity,null,chat.id,false);
            }
        }

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_contact_chat_settings;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public void initView() {
        super.initView();
        setTitle(getString(R.string.chat_details));
        if (getIntent() != null) {
            chatInfo = getIntent().getParcelableExtra("chat");
        } else {
            chatInfo = new ChatInfo();
        }
        binding.headerImageView.setTextSize(27);
        viewModel.setContext(this);
        //刷新UI
        syncChatInfo();
        //黑名单请求
        binding.blockedLayout.setVisibility(View.GONE);
        syncUserFullInfo();
    }

    private void syncUserFullInfo() {
        TelegramManager.getTelegramManager().requestContactFullInfo(this, chatInfo.id, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                if (obj != null) {
                    userFullInfo = obj;
                    binding.blockedLayout.setVisibility(View.VISIBLE);
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private void syncChatInfo() {
        if (chatInfo != null) {
            ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(chatInfo.id);
            if (chat != null) {
                chatInfo = chat;
            }
        }
        resetUI();
    }

    public void resetUI() {
        binding.muteSwitch.setOnCheckedChangeListener(null);
        binding.topSwitch.setOnCheckedChangeListener(null);
        binding.blockedSwitch.setOnCheckedChangeListener(null);
        if (chatInfo != null) {
            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(chatInfo.id);
            if (user != null) {
                binding.headerImageView.showUser(user);
                binding.nameText.setText(user.displayName());
                if (!StringUtils.isEmpty(user.username)) {
                    binding.userNameText.setText("@" + user.username);
                } else {
                    binding.userNameText.setText(" ");
                }
            }
            binding.muteSwitch.setChecked(chatInfo.default_disable_notification);
            binding.topSwitch.setChecked(chatInfo.is_pinned);
            if (chatInfo.id == TelegramManager.TG_USERID_SYSTEM_NOTICE) {
                binding.blockedLayout.setVisibility(View.GONE);
                binding.systemRoleText.setVisibility(View.VISIBLE);
                binding.createGroupLayout.setVisibility(View.GONE);
            } else {
                binding.systemRoleText.setVisibility(View.GONE);
                binding.createGroupLayout.setVisibility(View.VISIBLE);
            }
        }
        if (userFullInfo != null) {
            binding.blockedSwitch.setChecked(userFullInfo.is_blocked);
        } else {
            binding.blockedSwitch.setChecked(false);
        }
        //开关事件
        binding.muteSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                muteSwitchClick();
            }
        });
        binding.topSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                pinSwitchClick();
            }
        });
        binding.blockedSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                blockSwitchClick();
            }
        });
    }

    private void muteSwitchClick() {
        showProgress();
        TelegramManager.getTelegramManager().toggleChatDisableNotification(this, chatInfo.id, !chatInfo.default_disable_notification, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    syncChatInfo();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                resetUI();
            }
        });
    }

    private void pinSwitchClick() {
        showProgress();
        TelegramManager.getTelegramManager().toggleChatIsPinned(this, chatInfo.id, !chatInfo.is_pinned, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    syncChatInfo();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                resetUI();
            }
        });
    }

    private void blockSwitchClick() {
        if (userFullInfo == null) {
            resetUI();
            syncUserFullInfo();
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(userFullInfo.is_blocked ? getString(R.string.remove_black_list_question) : getString(R.string.join_black_list_question));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        blockUser();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                resetUI();
            }
        });
        dialog.show();
    }

    private void blockUser() {
        showProgress();
        TelegramManager.getTelegramManager().blockUser(this, chatInfo.id, !userFullInfo.is_blocked, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    userFullInfo.is_blocked = !userFullInfo.is_blocked;
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                resetUI();
            }
        });
    }

    private void toggleChatDeleteConfirm() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(getString(R.string.clear_chat_history_question));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toggleChatDelete();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void toggleChatDelete() {
        showProgress();
        TelegramManager.getTelegramManager().deleteChatHistory(this, chatInfo.id, false, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    ToastUtils.showShort(getString(R.string.chat_histor_cleared));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @OnClick({R.id.infoLayout, R.id.createGroupLayout, R.id.reportLayout, R.id.cleanMsgLayout, R.id.backgroundLayout,R.id.recommendLayout})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.infoLayout:
                if (chatInfo != null) {
                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(chatInfo.id);
                    if (user != null)
//                        ContactDetailActivity.start(this, user);
                    ContactDetailSingleActivity.start(this, user);
                }
                break;
            case R.id.createGroupLayout:
                ContactChooseActivity.startWithCreateSuperGroup(this, chatInfo.id);
                break;
            case R.id.reportLayout:
                PreviewWebViewActivity.loadUrl(this, getString(R.string.complaint_text), Constants.KHostEReport);
                break;
            case R.id.cleanMsgLayout:
                toggleChatDeleteConfirm();
                break;
            case R.id.backgroundLayout:
                SettingBackgroudActivity.start(this, chatInfo);
                break;
            case R.id.recommendLayout:
                if (chatInfo != null) {
                    UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(chatInfo.id);
                    if (user != null){
                        MessageInfo messageInfo = new MessageInfo();
                        MessageContent content = new MessageContent();
                        MobileContactInfo contactInfo = new MobileContactInfo();
                        contactInfo.first_name = user.first_name;
                        contactInfo.last_name = user.last_name;
                        contactInfo.user_id = user.id;
                        contactInfo.phone_number = user.phone_number;
                        content.contact = contactInfo;
                        messageInfo.content = content;
                        messageInfo.messageType = TelegramManager.MessageType.MessageType_Contact;

                        Intent intent = new Intent(this, ForwardActivity.class);
                        intent.putExtra("message", messageInfo);
                        startActivity(intent);
                        finish();
                    }
                }


                break;
        }
    }

}